<template>
    <eui-page-frame :topHeight="150" :bottomHeight="90" withOutBorder="true">
        <template #top>
            <view class="content-img">
                <eui-navbar ref="EuiNavBar" :title="title" color="#000000" backgroundColor="#FFFFFF" displayable="true"
                    :storeName="getRelatedName('rdsStores', sUserStore)" :storeId="sUserStore" />
            </view>
        </template>
        <eui-page-content>
            <view class="footer-view">
                <eui-card title="基本信息" showTitleLine="true" top-margin="0" h-padding="20" type="upDownSingle">
                    <template #content>
                        <view class="m-main-top">
                            <eui-text v-model="mainData.c_provider" type="titlename" title="供应商"
                                :name="getRelatedName('rdsProviders', mainData.c_provider)" occupy />
                            <eui-text v-model="mainData.c_wno" type="titlename" title="仓库"
                                :name="getRelatedName('rdsWnos', mainData.c_wno)" occupy />
                            <eui-text v-model="c_n_rec_total" type="price" title="已收正品数量" />
                            <eui-text v-model="c_sku_rec_total" type="name" title="已收品种数" />
                            <eui-text v-model="c_n_rec_free_total" type="price" title="已收赠品数量" />
                        </view>
                    </template>
                </eui-card>
                    <eui-card title="商品信息" showTitleLine="true" h-padding="20" type="detail">
                        <view v-for="(item, index) in detailData" :key="index">
                            <view class="m-list-top">
                                <eui-text :value="`[${item.c_gcode}]${item.c_gname}`" type="name"
                                    :title="`${index + 1}. 商品`" occupy />
                                <eui-text v-model="item.c_barcode" type="name" title="条码" />
                                <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                    title="含量/单位" />
                                <eui-text v-model="item.c_n_confirm" type="price" title="订货数量" />
                                <eui-text v-model="item.c_n_free_confirm" type="price" title="赠品数量(订)" />
                                <eui-text v-model="item.c_n" type="price" title="收货数量"
                                    :valueStyle="(item.c_n !== 0 && item.c_n_confirm !== item.c_n) ? 'color: red' : 'color: black'" />
                                <eui-text v-model="item.c_n_free" type="price" title="赠品数量(收)" />
                                <eui-text v-model="item.c_product_dt" type="date" title="生产日期" />
                                <eui-text v-model="item.c_expired_dt" type="date" title="限用日期" />
                                <eui-text v-model="item.c_serial_no" type="name" title="批号" occupy />
                                <eui-text v-model="item.c_note" type="name" title="备注" />
                                <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                    v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;" occupy />
                            </view>
                        </view>
                        <view v-if="detailData.length === 0">
                            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min" />
                            <view class="no-data-text">暂无数据</view>
                        </view>
                    </eui-card>
            </view>
            <eui-popup ref="popupMessage" background-color="#f8f8f8" type="center">
                <view class="popup-content">
                    <view class="popup-title">提示</view>
                    <view v-for="(item, index) in processInFos" :key="index">
                        <eui-text :value="index + 1 + '. ' + item.BillId" type="id" title="单号" />
                        <eui-text :value="item.ErrInFo" type="name" style="white-space: pre-wrap;color:red"
                            title="错误信息" />
                    </view>
                </view>
            </eui-popup>
        </eui-page-content>
        <template #bottom>
            <view class="bt-button">
                <eui-button type="max" single-tag="audit" :title="sysConfig.isApprove ? '审批' : '审核'"
                    @buttonClick="buttonClick"
                    :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'" />
            </view>
        </template>
    </eui-page-frame>
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import service from '@/common/service';
import { getRelatedName } from '../components/RelatedName.js';
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import { groupBy } from '@/hooks/useUtils';
import { getRdsSysConfig } from '@/hooks/init';
import { mapState, mapMutations } from 'vuex'
import { onLoad } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const loginStore = useLoginStore();

const sUserStore = ref('');
const c_sku_rec_total = ref(0);
const c_n_rec_total = ref(0);
const c_n_rec_free_total = ref(0);
const title = ref('验收详情');
const sysConfig = ref({
    isApprove: false,//商品验收单是否审批
});

const collectionId = ref('');
const mainData = ref({});
const detailData = ref([]);
const mainDataList = ref([]);
const listManager = ref([]);
const groupData = ref([]);
const detailDataMiddleList = ref([]);
const processInFos = ref([]);

onLoad(async (option) => {
    await getSysConfig();
    sUserStore.value = option.storeId;
    if (option.c_id && option.c_id !== 'undefined') {
        title.value = option?.c_id + '详情';
        mainData.value.c_id = option.c_id;
        service.enjoyShowLoading('正在加载...');
        await billQuery(option.c_id);
        service.enjoyHideLoading();
    } else if (option.collectionId && option.collectionId !== 'undefined') {
        console.log("option.collectionId", option.collectionId)
        collectionId.value = option.collectionId;
        await queryRecById(option.collectionId);
    }
})

const getSysConfig = async () => {
    sysConfig.value.isApprove = await getRdsSysConfig("单据是否审批", "商品验收单") === '是';
};

const buttonClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'audit':
            // 审核
            if (collectionId.value) {
                if (sysConfig.value.isApprove && mainData.value.c_status === '0') { // 批量审批
                    await batchApprove();
                }
                if (!sysConfig.value.isApprove && mainData.value.c_status === '0') { // 批量审核
                    await batchAuditBill();
                }
            } else {
                if (detailData.value.length <= 0) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: '商品不能为空！'
                    });
                    return;
                }
                const req = {
                    BillId: mainData.value.c_id,
                    UserNo: loginStore.sUser,
                    StoreId: mainData.value.c_store_id,
                }

                if (sysConfig.value.isApprove && mainData.value.c_status === '0') { // 审批
                    await approve(req);
                }
                if (!sysConfig.value.isApprove && mainData.value.c_status === '0') { // 审核
                    await auditBill(req);
                }
            }
            //更新集单表状态已完成
            await updateCollectionStatus('2');
            break;
    }
};
const billQuery = async (billId) => {
    if (!billId || collectionId.value) {
        return;
    }
    const req = {
        BillId: billId,
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillQuery', req, '701');
    if (result.ds.length > 0) {
        mainData.value = result.ds[0];
        detailData.value = result.ds1;
        c_sku_rec_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
        c_n_rec_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
        c_n_rec_free_total.value = result.ds1.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);
    } else {
        await uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '暂无数据',
            mask: true,
        });
    }
};

const queryRecById = async (billId) => {
    // 查询集单号下验收单和商品
    if (!billId) {
        return;
    }
    const result = await rdsRequest(rdsUrl.scApi, '集单收货', 'QueryRecById', billId, '');
    if (result?.ds.length > 0) {
        mainData.value = result.ds[0];
        mainDataList.value = result.ds;
        const detailDataList = result.ds1;
        console.log("detailDataMiddleList", detailDataList)
        groupData.value = groupBy(detailDataList, ['c_barcode']).map(g => (
            {
                // ...g.keys,
                ...g.groups[0],
                c_n: g.groups.reduce((p, c) => p + c.c_n, 0),
                c_n_pack: g.groups.reduce((p, c) => p + c.c_n_pack, 0),
                c_n_odd: g.groups.reduce((p, c) => p + c.c_n_odd, 0),
                // c_n_free_confirm: g.groups.reduce((p, c) => p + c.c_n_free_confirm, 0)
            }
        ));

        c_sku_rec_total.value = groupData.value.reduce((pre, current) => pre + (current.c_n > 0 || current.c_n_free > 0), 0);
        c_n_rec_total.value = detailDataList.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
        c_n_rec_free_total.value = detailDataList.reduce((pre, current) => pre + (current.c_n_free ?? 0), 0);

        detailData.value = groupData.value;
    } else {
        await uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '暂无数据',
            mask: true,
        });
    }
};
// 审批
const approve = async (req) => {
    if (mainData.value.c_approve_status === "1") {
        await uni.showModal({
            title: ' 提示',
            content: '请确认，单据[' + req.BillId + ']发起审批?',
            showCancel: true,
            success: async (res) => {
                if (res.confirm) {
                    await sendApprove();
                }
            }
        });
    } else {
        const item = {
            c_approve_status: mainData.value.c_approve_status,
            Id: mainData.value.c_id,
            UserNo: loginInfo.sUser,
            StoreId: mainData.value.c_store_id,
            AppParam: '商品验收单',
        }
        const request = {
            Id: req.BillId,
            UserNo: loginInfo.sUser,
            StoreId: mainData.value.c_store_id,
        }
        // apps.ApprovePath(request, item, res => { }, res => { });
    }
};

const auditBill = async (req) => {
    if (mainData.value.c_status === '0') {
        await uni.showModal({
            title: ' 提示',
            content: '请确认，审核单据[' + req.BillId + ']?',
            showCancel: true,
            success: async (res) => {
                if (res.confirm) {
                    service.enjoyShowLoading('正在审核...');
                    await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillAudit', req, '701');
                    service.enjoyHideLoading();
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: '审核成功！'
                    });
                    await billQuery(mainData.value.c_id);
                }
            }
        });
    }
};

const sendApprove = async () => {
    const ApproveBills = {
        AppPage: "/modules/ic/rec/rec/list",
        AppParam: "商品验收单",
        AppUsers: [],
        BillId: mainData.value.c_id,
        BillKey: mainData.value.c_id,
        BillRealType: "商品验收单",
        BillType: "商品验收单",
        CFGName: "商品验收单",
        FlowGuid: "",
        FlowName: "商品验收单",
        HtmlContent: "",
        HtmlMobileContent: "",
        IsMainFlow: true,
        IsCanTempApp: false,
        IsSelected: true,
        IsTempApp: false,
        MdCode: "rds_ic_gds_rec",
        NoticType: "邮件",
        ProjectName: "RDS", // OA\RMIS\RMISNew,
        StoreId: mainData.value.c_store_id,
        AppReqUserNo: loginInfo.sUser,
        UserNo: loginInfo.sUser,
        TempTitle: `单据:${mainData.value.c_id}`,
        // ApproveServiceUrl: Url.EnjoyRMIS,
    }
    const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'SendApprove', ApproveBills, '701');
    if (approveResult.Result) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '发送审批成功！'
        });
        await billQuery(mainData.value.c_id);
    }
};
const batchAuditBill = async () => {
    await uni.showModal({
        title: ' 提示',
        content: '请确认，审核单据[' + mainDataList.value.map(x => x.c_id).join(',') + ']?',
        showCancel: true,
        success: async (res) => {
            if (res.confirm) {
                let ObjectData = [];
                mainDataList.value.filter(x => x.c_status === '0').map(x => {
                    ObjectData.push({ BillId: x.c_id, UserNo: loginInfo.sUser })
                })
                service.enjoyShowLoading('正在审核...');
                const auditResult = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillAudits', ObjectData, '701');
                service.enjoyHideLoading();
                const errorList = auditResult.processInFos.filter(x => x.Flag === '0');
                if (errorList.length > 0) {
                    processInFos.value = errorList;
                    $refs.popupMessage.open('center');
                } else {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: '审核成功！'
                    });
                    await queryRecById(collectionId.value);
                }

            }
        }
    });
};
const batchApprove = async () => {
    await uni.showModal({
        title: ' 提示',
        content: '请确认，单据[' + mainDataList.value.map(x => x.c_id).join(',') + ']发起审批?',
        showCancel: true,
        success: async (res) => {
            if (res.confirm) {
                await batchSendApprove();
            }
        }
    });
};
const batchSendApprove = async () => {
    const AppBillInFos = mainDataList.value.map(x => {
        return {
            BillKey: x.c_id,
            BillId: x.c_id
        }
    });
    const ApproveBills = {
        AppBillInFos: AppBillInFos,
        AppParam: "商品验收单",
        AppUserNo: loginInfo.sUser,
        BillType: "商品验收单",
        CFGParam: "商品验收单",
        MdCode: "rds_ic_gds_rec",
        ApprovePage: "/modules/ic/rec/rec/detail",
        MdName: "商品验收单",
        StoreId: mainData.value.c_store_id,
        ProjectName: "rds"
    }
    const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'BatchApproveSend', ApproveBills, '701');

    const errorList = approveResult.processInFos.filter(x => !x.ErrInFo);
    if (errorList.length > 0) {
        processInFos.value = errorList;
        $refs.popupMessage.open('center');
    } else {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '发送审批成功！'
        });
        await queryRecById(collectionId.value);
    }
};
const updateCollectionStatus = async (status) => {
    if (collectionId.value) {
        const req = {
            BillId: collectionId.value,
            Status: status,
        }
        await rdsRequest(rdsUrl.scApi, '集单收货', 'UpdateCollectionStatus', req, '');
    }
}
</script>

<style lang="scss" scoped>
@import '@/main.scss';

::v-deep .white-main {
    margin: 20rpx 0;
}

.footer-view {
    width: 100%;
    flex: 1;
}

.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.m-main-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
    padding: 10rpx 0rpx;
}

.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-content {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0;
    width: 100%;
    background-color: #f8f8f8;
}

.popup-height {
    width: 200px;
}

.popup-title {
    width: 100%;
    flex: 1;
    color: #666666;
    font-size: 0.8em;
    line-height: 2em;
    text-align: center;
    margin: 5px 0px 0px;
    border-bottom: 1px solid #cccccc;
}
</style>
